class Register{
    constructor(){
        // 选择各种元素
        this.user = document.querySelector(".user");
        this.pass = document.querySelector(".pass");
        this.tel = document.querySelector(".tel");
        this.email = document.querySelector(".ema");
        this.sub = document.getElementById("submit");
        this.msg = document.querySelector(".msg");
        // 提前准备接口
        this.url = "http://api.icodeilife.cn:81/user";
        //正则验证
        this.test();
        // 绑定事件
        this.addEvent();
    }
    test(){
		//用户名验证
		this.user.oninput = function(){
			var reg = /^[\w]{6,12}$/;
			if(reg.test(this.value)){
				this.nextElementSibling.innerHTML = "";
			}else{
				this.nextElementSibling.innerHTML = "请输入6到12位数字字母下划线";
			}
		}
		//密码验证
		this.pass.oninput = function(){
			var reg = /^[\w]{6,12}$/;
			if(reg.test(this.value)){
				this.nextElementSibling.innerHTML = "";
			}else{
				this.nextElementSibling.innerHTML = "请输入6到12位数字字母下划线";
			}
		}
		//手机号验证
		this.tel.oninput = function(){
			var reg = /^1[3-9]\d{9}$/;
			if(reg.test(this.value)){
				this.nextElementSibling.innerHTML = "";
			}else{
				this.nextElementSibling.innerHTML = "不符合手机号码规则";
			}
		}
		//邮箱验证
		this.email.oninput = function(){
			var regQ = /^[1-9][0-9]{9}\@(qq)\.com$/;
			var regA = /^[a-zA-Z]{1,15}\@((mail)|(163)|(126)|(139)|(189)|(163))\.com$/;
			if(regQ.test(this.value) || regA.test(this.value)){
				this.nextElementSibling.innerHTML = "";
			}else{
				this.nextElementSibling.innerHTML = "不符合邮箱规则";
			}
		}
    }
    addEvent(){
        var that = this;
        this.sub.onclick = function(){
            // 注册请求之前获取输入框内容
            that.u = that.user.value;
            that.p = that.pass.value;
            that.t = that.tel.value;
            that.e = that.email.value;
            that.load();
        }
    }
    load(){
        ajax({
            url:this.url,
            data:{  
                type: "register",
                user: this.u,
                pass: this.p,
                tel: this.t,
                email: this.e
            }
        }).then((res)=>{
            // console.log(res);
            this.res = JSON.parse(res);
            this.display();
        })
    }
    display(){
        if(this.res.code == 1){
            this.msg.innerHTML = this.res.msg + "，3秒后到登录页面";
            setTimeout(()=>{
                location.href = "login.html";
            },3000);
        }else{
            this.msg.innerHTML = this.res.msg + "，请重新输入";
        }
    }
}

new Register;